import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'
import { ElMessage } from 'element-plus'
import instance from '@/api'
interface TableDataType {
    index: number
    list_index: number
    name: string
    phone: string
    address: string
    type: string
    shop: string
    order_count: number
    tags: Array<string>
    shopName: string
    contact_time: string
    due_time: string
}
export default function(tableData: TableDataType[], keyWord: any, filterForm: any){
// 导出功能修改
const exportExcel = (data: TableDataType[], fileName: string) => {
    try {
      const headers = [
        '序号', '客户姓名', '联系电话', '客户地址', '客户类型',
        '所属分店', '会员标签', '开始时间', '到期时间'
      ]
      const rows = data.map(item => [
        item.index,
        item.name,
        item.phone,
        item.address,
        item.type,
        item.shopName,
        item.tags?.join(',') || '无',
        item.contact_time,
        item.due_time
      ])
      const workbook = XLSX.utils.book_new()
      const worksheet = XLSX.utils.aoa_to_sheet([headers, ...rows])
      worksheet['!cols'] = [
        { wch: 6 }, { wch: 10 }, { wch: 13 }, { wch: 40 },
        { wch: 10 }, { wch: 12 }, { wch: 25 }, { wch: 20 }, { wch: 20 }
      ]
  
      XLSX.utils.book_append_sheet(workbook, worksheet, '客户数据')
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
      const blob = new Blob([excelBuffer], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      })
      saveAs(blob, `${fileName}_${new Date().toISOString().slice(0,10)}.xlsx`)
      ElMessage.success('导出成功')
    } catch (error) {
      console.error('导出失败:', error)
      ElMessage.error('导出失败，请稍后重试')
    }
}
  
// 导出当前页
const exportCurrentPage = () => {
  exportExcel(tableData, '当前页客户数据')
}
  
// 导出全部数据
const exportAllData = async () => {
  try {
    ElMessage.info('正在生成全量数据，请稍候...')
    const params = {
      name: keyWord.value.trim() || undefined,
      shop: filterForm.shop ? Number(filterForm.shop) : undefined,
      type: filterForm.customerType || undefined,
      exportAll: true // 添加导出标记
    }
    const resp = await instance.get<TableDataType[]>('/api/member/export', { params })
    if (resp.status === 200) {
      console.log(resp)
      exportExcel(
        resp.data.map((item, index) => ({ ...item, index: index + 1 })),
        '全部客户数据'
      )
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出全部数据失败')
  }
}
  return { exportCurrentPage, exportAllData }
}